import axios from 'axios'
import { diffTime } from '@/utils/constant'
import store from '@/store'

const request = axios.create({
  baseURL: 'http://127.0.0.1:8888/api/private/v1/',
  timeout: 3000
})

// 请求拦截器
request.interceptors.request.use((config) => {
  if (localStorage.getItem('token')) {
    if (diffTime()) {
      store.dispatch('loginOut')
      return Promise.reject(new Error('token失效'))
    }
  }
  // 请求时将token放在请求头上
  config.headers.Authorization = localStorage.getItem('token')
  return config
}, (error) => {
  return new Promise(new Error(error))
})

export default request
